package liantiaoxifen.client;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Controller {
    private Socket socket;
    private Scanner scan;
    private PrintWriter pw;
    private BufferedReader br;
    public Controller(){
        try {
            System.out.println("正在连接服务器~");
            socket=new Socket("localhost",8000);
            System.out.println("连接服务器成功！");
        } catch (IOException e) {
            System.out.println("连接服务器失败！");
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            scan=new Scanner(System.in);
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw =new OutputStreamWriter(out);
            BufferedWriter bw=new BufferedWriter(osw);
            pw=new PrintWriter(bw,true);

            InputStream in=socket.getInputStream();
            InputStreamReader isr=new InputStreamReader(in);
            br=new BufferedReader(isr);
            Service service=new Service(br,pw);
            System.out.println("请输入你想要使用的业务 1.登录 2.注册");
            int yw;
            while (true){
                yw=scan.nextInt();
                scan.nextLine();
                if (yw!=1&&yw!=2) {
                    System.out.println("请输入 1 或者 2");
                    continue;
                }
                break;
            }
            if (yw==1){
                pw.println(1);
                service.loginhander();
            }else if (yw==2){
                pw.println(2);
                int i= service.registerhander();
                if (i==1){
                    System.out.println("接下来开始登录！");
                    service.loginhander();
                }
            }

        } catch (IOException e) {
            System.out.println("");
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("");
                e.printStackTrace();
            }
        }
    }
}
